package my.rpc.common.codec;

import my.rpc.common.util.SerializationUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * RPC 编码器
 * @author fengbo
 * @date 2017/11/2
 */
public class RpcEncoder<T> extends MessageToByteEncoder<T> {

    private Class<T> genericClass;

    public RpcEncoder(Class<T> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) {
        // 用来判断 in 是否属于 genericClass 的实例
        if (genericClass.isInstance(in)) {
            byte[] data = SerializationUtils.serialize(in);
            out.writeInt(data.length);
            out.writeBytes(data);
        }
    }
}